<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>账户设置</h1>
      <p>管理您的个人信息和账户安全</p>
    </div>

    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-tooltip content="编辑您的基本资料信息">
            <i class="el-icon-info-circle"></i>
          </el-tooltip>
        </div>
      </template>

      <el-row :gutter="30">
        <el-col :span="8" :xs="24">
          <div class="avatar-container">
            <div class="avatar-wrapper">
              <el-avatar
                :size="140"
                :src="user.avatar || defaultAvatar"
                class="user-avatar"
              />
              <label class="change-avatar-btn">
                <i class="el-icon-camera"></i>
                <input
                  type="file"
                  accept="image/*"
                  class="avatar-upload"
                  hidden
                  @change="handleAvatarChange"
                />
              </label>
            </div>
            <p class="username-display">{{ user.username }}</p>
            <p class="username-hint text-muted">用户名不可修改</p>
          </div>
        </el-col>

        <el-col :span="16" :xs="24">
          <el-form
            ref="formRef"
            :model="user"
            :rules="rules"
            label-width="100px"
            class="profile-form"
          >
            <el-row :gutter="20">
              <el-col :span="12" :xs="24">
                <el-form-item label="昵称" prop="displayName">
                  <el-input
                    v-model="user.displayName"
                    placeholder="请输入您的昵称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="user.email" placeholder="请输入您的邮箱" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12" :xs="24">
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="user.phone"
                    placeholder="请输入您的手机号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item label="性别">
                  <el-radio-group v-model="user.gender" class="radio-group">
                    <el-radio label="男" border>男</el-radio>
                    <el-radio label="女" border>女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="角色">
              <el-select v-model="user.role" placeholder="请选择角色">
                <el-option label="管理者" value="admin"></el-option>
                <el-option label="编辑" value="editor"></el-option>
                <el-option label="订阅者" value="subscriber"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="个人简介">
              <el-input
                v-model="user.bio"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介，让大家更好地了解你..."
              />
            </el-form-item>

            <el-form-item class="form-actions">
              <el-button type="primary" @click="saveProfile" class="save-btn">
                <i class="el-icon-check"></i> 保存信息
              </el-button>
              <el-button @click="resetForm" class="reset-btn">
                <i class="el-icon-refresh"></i> 重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <!-- 文章管理部分 -->
    <el-card class="articles-card">
      <template #header>
        <div class="card-header">
          <span>我的文章</span>
          <el-tooltip content="管理您的文章">
            <i class="el-icon-document"></i>
          </el-tooltip>
        </div>
      </template>

      <div class="article-table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          stripe
          class="article-table"
        >
          <!-- 文章封面 -->
          <el-table-column label="封面" width="100" align="center">
            <template #default="scope">
              <el-image
                :src="scope.row.cover"
                :alt="scope.row.title"
                class="article-cover"
                fit="cover"
              />
            </template>
          </el-table-column>

          <!-- 文章标题 -->
          <el-table-column label="标题" prop="title" min-width="200" />

          <!-- 关键字 -->
          <el-table-column label="关键字" prop="slug" min-width="150" />

          <!-- 评论状态 -->
          <el-table-column
            label="评论状态"
            prop="commentStatus"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-tag
                :type="scope.row.commentStatus === 'open' ? 'success' : 'info'"
                effect="light"
                style="cursor: pointer"
                @click="toggleCommentStatus(scope.row)"
              >
                {{ scope.row.commentStatus === "open" ? "开启" : "关闭" }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 是否置顶 -->
          <el-table-column
            label="是否置顶"
            prop="isTop"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.isTop"
                active-color="#13ce66"
                inactive-color="#898282"
                @change="toggleTopStatus(scope.row)"
              />
            </template>
          </el-table-column>

          <!-- 文章发布状态 -->
          <el-table-column
            label="状态"
            prop="status"
            width="100"
            align="center"
          >
            <template #default="scope">
              <div style="display: flex; flex-direction: column; gap: 5px; align-items: center;">
                <el-tag
                  :type="scope.row.status === 'published' ? 'success' : 'info'"
                  style="width: 100%; cursor: pointer;"
                  @click="updateStatus(scope.row, 'published')"
                >
                  已发布
                </el-tag>
                <el-tag
                  :type="scope.row.status === 'draft' ? 'warning' : 'info'"
                  style="width: 100%; cursor: pointer;"
                  @click="updateStatus(scope.row, 'draft')"
                >
                  草稿
                </el-tag>
                <el-tag
                  :type="scope.row.status === 'trash' ? 'danger' : 'info'"
                  style="width: 100%; cursor: pointer;"
                  @click="updateStatus(scope.row, 'trash')"
                >
                  回收站
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <!-- 发布时间 -->
          <el-table-column label="发布时间" prop="publishTime" min-width="160">
            <template #default="scope">
              {{ scope.row.publishTime || "未发布" }}
            </template>
          </el-table-column>

          <!-- 更新时间 -->
          <el-table-column label="更新时间" prop="updateTime" min-width="160">
          </el-table-column>

          <!-- 操作 -->
          <el-table-column
            label="操作"
            width="180"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                icon="Edit"
                @click="handleEdit(scope.row)"
                class="edit-btn"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="delete-btn"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="pagination.pageNum"
            :page-size="pagination.pageSize"
            :page-sizes="pagination.pageSizes"
            :total="pagination.total"
            :layout="pagination.layout"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            class="pagination"
          />
        </div>
      </div>
    </el-card>

    <el-card class="security-card">
      <template #header>
        <div class="card-header">
          <span>安全设置</span>
          <el-tooltip content="管理您的账户安全选项">
            <i class="el-icon-shield"></i>
          </el-tooltip>
        </div>
      </template>

      <div class="security-content">
        <div class="security-item">
          <div class="security-icon">
            <i class="el-icon-key"></i>
          </div>
          <div class="security-info">
            <h3>密码管理</h3>
            <p class="text-muted">定期更改密码可提高账户安全性</p>
          </div>
          <el-button
            type="primary"
            plain
            @click="changePassword"
            class="action-btn"
          >
            修改密码
          </el-button>
        </div>

        <div class="security-item">
          <div class="security-icon">
            <i class="el-icon-switch-button"></i>
          </div>
          <div class="security-info">
            <h3>退出登录</h3>
            <p class="text-muted">安全退出当前登录状态</p>
          </div>
          <el-button type="danger" plain @click="logout" class="action-btn">
            退出登录
          </el-button>
        </div>
      </div>

      <el-dialog
        v-model="passwordDialogVisible"
        title="修改密码"
        width="500px"
        :before-close="handlePasswordDialogClose"
        class="password-dialog"
      >
        <el-form
          ref="passwordFormRef"
          :model="passwordData"
          :rules="passwordRules"
          label-width="120px"
          class="password-form"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordData.oldPassword"
              type="password"
              show-password
              placeholder="请输入原密码"
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordData.newPassword"
              type="password"
              show-password
              placeholder="请输入新密码(至少5位)"
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="rePassword">
            <el-input
              v-model="passwordData.rePassword"
              type="password"
              show-password
              placeholder="请再次输入新密码"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="passwordDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPasswordChange"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElTooltip } from "element-plus";

import defaultAvatar from "@/assets/images/default-avatar.jpg"; // 默认头像
import {
  getUserInfoService,
  updateUserInfoService,
  logoutService,
  updatePasswordService,
} from "@/api/user.js";

import { getArticleListService,
        updateArticleCommentStatusService,
        updateArticleTopService ,
        updateArticleStatusService,
        deleteArticleService
      } from "@/api/post.js";
  
import useUserInfoStore from "@/stores/userInfo.js";
import { useTokenStore } from "@/stores/token.js";
import { useRouter } from "vue-router";

// 路由对象
const router = useRouter();
// 用户信息表单引用
const formRef = ref();
// 修改密码对话框显示控制
const passwordDialogVisible = ref(false);
// 密码表单引用
const passwordFormRef = ref();

// 用户信息数据
const user = reactive({
  username: "",
  displayName: "",
  email: "",
  role: "",
  phone: "",
  gender: "",
  bio: "",
  avatar: "",
});

// 用户密码数据
const passwordData = reactive({
  oldPassword: "",
  newPassword: "",
  rePassword: "",
});

// 表单验证规则
const rules = {
  displayName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 20, message: "昵称长度为2-20个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

// 自定义确认密码的校验函数
const rePasswordValid = (rule, value, callback) => {
  if (value == null || value === "") {
    return callback(new Error("请再次确认密码"));
  }
  if (passwordData.newPassword !== value) {
    return callback(new Error("两次输入密码不一致"));
  }
  callback();
};

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { min: 5, message: "密码长度不能少于5位", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 5, message: "密码长度不能少于5位", trigger: "blur" },
  ],
  rePassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    { validator: rePasswordValid, trigger: "blur" },
  ],
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await getUserInfoService();
    if (res.code === 0) {
      Object.assign(user, res.data);
      useUserInfoStore().setInfo(res.data);
    } else {
      console.log("获取用户信息失败:", res.message);
    }
  } catch (error) {
    console.error("获取用户信息异常:", error);
  }
};

// 保存用户信息
const saveProfile = async () => {
  try {
    await formRef.value.validate();
    const response = await updateUserInfoService(user);
    if (response.code === 0) {
      useUserInfoStore().setInfo(response.data);
      ElMessage.success("保存成功!");
    } else {
      ElMessage.error(response.message || "保存失败");
      console.log("保存用户信息失败:", response.message);
    }
  } catch (error) {
    console.log("表单验证失败:", error);
  }
};

// 重置个人信息表单
const resetForm = () => {
  formRef.value.resetFields();
  const userInfoStore = useUserInfoStore();
  if (userInfoStore.info) {
    Object.assign(user, userInfoStore.info);
  }
};

// 文章管理相关数据
const tableData = ref([]);
const loading = ref(false);
// 分页相关数据
const pagination = reactive({
  pageSize: 5,
  pageNum: 1,
  total: 0,
  pageSizes: [5, 10, 20, 50],
  layout: "total, sizes, prev, pager, next, jumper",
});

// 获取文章列表数据
const getArticles = async () => {
  loading.value = true;
  let parmas = {
    pageNum: pagination.pageNum,
    pageSize: pagination.pageSize,
  };
  try {
    const result = await getArticleListService(parmas);
    //渲染表格数据
    tableData.value = result.data.items.map((item) => ({
      id: item.id,
      cover: item.coverImage,
      title: item.title,
      slug: item.slug,
      commentStatus: item.commentStatus,
      isTop: item.isTop === 1,
      status: item.status,
      publishTime: item.publishedAt,
      updateTime: item.updatedAt || item.createdAt,
    }));
    // 更新分页总数
    pagination.total = result.data.total;
  } catch (error) {
    console.error("获取文章列表失败:", error);
    ElMessage.error("获取文章列表失败");
  } finally {
    loading.value = false;
  }
};

// 分页变更处理
const handlePageChange = (pageNum) => {
  pagination.pageNum = pageNum;
  getArticles();
};

// 每页条数变更处理
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.pageNum = 1; // 重置到第一页
  getArticles();
};

// 切换评论状态
const toggleCommentStatus = async (row) => {
  const originalStatus = row.commentStatus;
  try {
    row.commentStatus = row.commentStatus === "open" ? "closed" : "open";
    
    await updateArticleCommentStatusService(row.commentStatus, row.id);
    
    ElMessage.success(
      `评论状态已更新为: ${row.commentStatus === "open" ? "开启" : "关闭"}`
    );
  } catch (error) {
    // 恢复原始状态
    row.commentStatus = originalStatus;
    console.error("更新评论状态失败:", error);
    ElMessage.error("更新评论状态失败，请稍后重试");
  }
};

// 切换置顶状态
const toggleTopStatus = async (row) => {
  const originalTopStatus = row.isTop;
  try {
    await updateArticleTopService(row.isTop ? 1 : 0, row.id);
    ElMessage.success(`置顶状态已更新为: ${row.isTop ? "置顶" : "取消置顶"}`);
  } catch (error) {
    // 恢复原始状态
    row.isTop = originalTopStatus;
    console.error("更新置顶状态失败:", error);
    ElMessage.error("更新置顶状态失败，请稍后重试");
  }
};

// 更新文章发布状态
const updateStatus = async (row, newStatus) => {
  // 如果状态相同，则不执行任何操作
  if (row.status === newStatus) {
    return;
  }
  
  const originalStatus = row.status;
  const statusMap = {
    published: '已发布',
    draft: '草稿',
    trash: '回收站'
  };
  
  try {
    row.status = newStatus;
    await updateArticleStatusService(newStatus, row.id);
    ElMessage.success(`文章状态已更新为: ${statusMap[newStatus]}`);
    await getArticles(); // 重新获取文章列表以确保数据同步
  } catch (error) {
    // 恢复原始状态
    row.status = originalStatus;
    console.error("更新状态失败:", error);
    ElMessage.error("更新状态失败，请稍后重试");
  }
};

// 修改文章
const handleEdit = (row) => {
  ElMessage.success(`正在编辑文章: ${row.title}`);
  router.push(`/articles/save/${row.id}`)
};

// 删除文章
const handleDelete =  (row) => {
  ElMessageBox.confirm(
    `确定要删除文章《${row.title}》吗？此操作不可撤销。`,
    "确认删除",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        await deleteArticleService(row.id);
        await getArticles(); // 更新列表
        ElMessage.success("文章已删除");
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
};

// 页面加载时获取用户信息
onMounted(() => {
  getUserInfo();
  getArticles();
});

// 修改密码
const changePassword = () => {
  passwordDialogVisible.value = true;
  resetPasswordForm();
};

// 修改密码的处理对话框关闭
const handlePasswordDialogClose = (done) => {
  ElMessageBox.confirm("确定要关闭吗？未保存的修改将会丢失", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      resetPasswordForm();
      done();
    })
    .catch(() => {
      // 取消关闭
    });
};

// 提交密码修改
const submitPasswordChange = async () => {
  try {
    await passwordFormRef.value.validate();
    const response = await updatePasswordService({
      oldPassword: passwordData.oldPassword,
      newPassword: passwordData.newPassword,
      rePassword: passwordData.rePassword,
    });

    if (response.code === 0) {
      ElMessage.success("密码修改成功");
      passwordDialogVisible.value = false;
      resetPasswordForm();
    } else {
      ElMessage.error(response.message || "密码修改失败");
    }
  } catch (error) {
    console.log("表单验证失败:", error);
  }
};

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
  passwordData.oldPassword = "";
  passwordData.newPassword = "";
  passwordData.rePassword = "";
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await logoutService();
      useTokenStore().removeToken();
      useUserInfoStore().removeInfo();
      ElMessage.success("已退出登录");
      router.push("/login");
    })
    .catch(() => {
      ElMessage.info("已取消退出登录");
    });
};
// 处理头像上传
const handleAvatarChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      user.avatar = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case 'published':
      return 'success';
    case 'draft':
      return 'warning';
    case 'trash':
      return 'info';
    default:
      return '';
  }
};
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.page-title {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-title p {
  color: #606266;
  font-size: 14px;
}

.profile-card,
.security-card,
.articles-card {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.profile-card:hover,
.security-card:hover,
.articles-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header .el-icon-info-circle,
.card-header .el-icon-shield,
.card-header .el-icon-document {
  color: #606266;
  font-size: 16px;
  cursor: pointer;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.avatar-wrapper {
  position: relative;
  margin-bottom: 20px;
}

.user-avatar {
  border: 4px solid #f5f7fa;
  transition: transform 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.03);
}

.change-avatar-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  transition: all 0.3s ease;
}

.change-avatar-btn:hover {
  background-color: #66b1ff;
  transform: scale(1.1);
}

.username-display {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.username-hint {
  font-size: 13px;
  margin-bottom: 0;
}

.profile-form {
  padding: 10px 0 20px 20px;
}

.form-actions {
  margin-top: 20px;
  padding-left: 100px;
}

.save-btn,
.reset-btn {
  margin-right: 15px;
  transition: all 0.2s ease;
}

.save-btn:hover {
  transform: translateY(-2px);
}

.reset-btn:hover {
  transform: translateY(-2px);
}

.security-content {
  padding: 15px 0;
}

.security-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px dashed #f0f0f0;
  transition: background-color 0.2s ease;
}

.security-item:last-child {
  border-bottom: none;
}

.security-item:hover {
  background-color: #cec2c2;
}

.security-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f5ff;
  color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 20px;
  flex-shrink: 0;
}

.security-info {
  flex-grow: 1;
}

.security-info h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 5px;
  font-weight: 500;
}

.security-info p {
  font-size: 13px;
  margin-bottom: 0;
}

.action-btn {
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: translateY(-2px);
}

.password-dialog {
  border-radius: 8px;
}

.password-form {
  margin-top: 15px;
}

.radio-group {
  display: flex;
  gap: 15px;
}

.text-muted {
  color: #909399;
}

/* 文章表格样式 */
.article-table-container {
  padding: 15px 0;
}

.article-table {
  width: 100%;
  margin-bottom: 20px;
}

/* 移除选中行样式，只保留悬浮效果 */
.article-table :deep(.el-table__body tr.el-table__row:hover td) {
  background-color: #6ac2d6 !important;
  transform: translateY(-2px) scale(1.01);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
  z-index: 1;
}

/* 为表格行添加初始状态以便动画生效 */
.article-table :deep(.el-table__body tr.el-table__row td) {
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.article-cover {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  transition: transform 0.3s ease;
}

.article-cover:hover {
  transform: scale(1.05);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.edit-btn {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .avatar-container {
    margin-bottom: 20px;
  }

  .form-actions {
    padding-left: 0;
    text-align: center;
  }

  .save-btn,
  .reset-btn {
    width: 45%;
    margin-right: 0;
  }

  .reset-btn {
    margin-left: 10px;
  }

  .security-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .security-icon {
    margin-bottom: 15px;
  }

  .action-btn {
    margin-top: 10px;
    width: 100%;
  }
}
</style>